import os
import sys
import json

def discover():
    cmd = 'sudo docker ps -a --format "{{.Names}}"'
    d = {}
    d['data'] = []
    with os.popen(cmd) as pipe:
        for line in pipe:
            info = {}
            info['{#CONTAINERNAME}'] = line.replace('\n', "")
            d['data'].append(info)
    print(json.dumps(d))

def status(container, action):
    if action == "ping":
        cmd = 'sudo docker inspect --format={{.State.Running}} %s' % (container)
        result = os.popen(cmd).read().replace("\n", "")
        if result == 'true':
            print(1)
        else:
            print(0)
    else:
        cmd = 'sudo docker stats %s --no-stream --format "{{.%s}}"' % (container, action)
        result = os.popen(cmd).read().replace("\n", "")
        if "%" in result:
            print(result.replace("%", ""))
        else:
            print(result)



if __name__ == '__main__':
    try:
        name, action = sys.argv[1], sys.argv[2]
        status(name, action)
    except:
        discover()

